/**
 * Copyright 2012 Brigham Young University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.byu.nlp.cluster.mom;

import com.google.common.annotations.VisibleForTesting;

import edu.byu.nlp.cluster.em.Maximizable;
import edu.byu.nlp.cluster.em.PartialCounts;
import edu.byu.nlp.math.optimize.ValueAndObject;
import edu.byu.nlp.stats.DirichletDistribution;

/**
 * @author rah67
 *
 */
public class EMMaximizable implements Maximizable<MoMParameters> {

	private double alpha;
	private double beta;
	private final MoMParameters prevParams;
	private final PartialCounts counts;
	private double logLikelihood;

	public EMMaximizable(double alpha, double beta, MoMParameters prevParams, PartialCounts counts,
			double logLikelihood) {
		this.alpha = alpha;
		this.beta = beta;
		this.prevParams = prevParams;
		this.counts = counts;
		this.logLikelihood = logLikelihood;
	}

	/** {@inheritDoc} */
	@Override
	public ValueAndObject<MoMParameters> maximize() {
		// FIXME : lower bound does not take into account observed data
		double lowerBound = logDensityAtPreviousParams() + logLikelihood;
		MoMParameters params = MoMParameters.fromWeights(counts.getYCounts(), counts.getXGivenYCounts(), false);
		return new ValueAndObject<MoMParameters>(lowerBound, params);
	}

	// This is the log p(lambda) + log(theta) part of the lower bound
	@VisibleForTesting
	double logDensityAtPreviousParams() {
		// FIXME : during annealing, these will need to be multiplied by T again!
		// log p(lambda)
		double lowerBound = DirichletDistribution.logDensitySymmetric(prevParams.getLogPOfY(), alpha);
		
		// log p(theta)
		for (int k = 0; k < prevParams.getLogPOfXGivenY().length; k++) {
			lowerBound += DirichletDistribution.logDensitySymmetric(prevParams.getLogPOfXGivenY()[k], beta);
		}
		return lowerBound;
	}

	@VisibleForTesting
	double[] getYCounts() {
		return counts.getYCounts();
	}

	@VisibleForTesting
	double[][] getXGivenYCounts() {
		return counts.getXGivenYCounts();
	}

	@VisibleForTesting
	double getLogLikelihood() {
		return logLikelihood;
	}
	
	
}
